package cn.falcon.fmobi.console.controller;

import cn.falcon.fmobi.admin.entity.ShiroUser;
import cn.falcon.fmobi.biz.service.AgentService;
import cn.falcon.fmobi.biz.service.CustomerService;
import cn.falcon.fmobi.biz.vo.FmobiUser;
import cn.falcon.fmobi.console.common.RestfulJsonModelAndView;
import cn.falcon.fmobi.console.common.Result;
import cn.falcon.fmobi.console.requestparam.AuthParam;
import cn.falcon.fmobi.dao.po.Advertiser;
import cn.falcon.fmobi.dao.po.Agent;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.security.Principal;

/**
 * @author George
 */
@Controller
public class AuthorCtrl {

    @Autowired
    MessageSource messageSource;


    @Autowired
    AgentService agencyService;

    @Autowired
    CustomerService advertiserService;
    /**
     * 用户登出
     *
     * @param req
     * @param
     * @return
     */
    @RequestMapping(value = "/logout", produces = "text/plain; charset=UTF-8")
    public ModelAndView logout(HttpServletRequest req) {
        Principal principal = req.getUserPrincipal();
        if (principal != null) {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
        }
        return RestfulJsonModelAndView.buildJsonModelAndView();
    }

    /**
     * 登录认证
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/auth", produces = "application/json; charset=UTF-8", method = RequestMethod.POST)
    public ModelAndView authLogin(@Valid @RequestBody AuthParam authParam) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(authParam.getUsername(),
            DigestUtils.md5DigestAsHex(authParam.getPassword().getBytes()));
        try {
            subject.login(token);
            Session session = SecurityUtils.getSubject().getSession();
            ShiroUser shiroUser = SecurityUtils.getSubject().getPrincipals().oneByType(ShiroUser.class);
            FmobiUser user = new FmobiUser();
            user.setRole(shiroUser.getRole());
            if(shiroUser.getActorType()==1){
                //代理商
                Agent agency = agencyService.getAgentById(shiroUser.getActorId());
                shiroUser.setName(agency.getName());
                user.setId(agency.getId());
                // 注意括号层次即运算优先级，先减后除
                user.setRebate(
                    (new BigDecimal(100).subtract(new BigDecimal(agency.getRebate()))).divide(new BigDecimal(100)));
            }else if(shiroUser.getActorType()==2){
                //广告主
                Advertiser advertiser = advertiserService.getAdvertiserById(shiroUser.getActorId());
                shiroUser.setName(advertiser.getCompanyName());
                user=advertiserService.readCustomerToUser(advertiser.getId());
            }else{
                shiroUser.setName("平台运营");
                session.setAttribute("fmobiUser", user);
                return RestfulJsonModelAndView.buildJsonModelAndView("/");
            }
            session.setAttribute("fmobiUser", user);
            return RestfulJsonModelAndView.buildJsonModelAndView("/campaign");

        } catch (UnknownAccountException e) {
            return RestfulJsonModelAndView.buildError(
                Result.ERR_AUTH_USERNAME_NOT_FOUND, messageSource
                    .getMessage("Result.err.auth.username.notfound", new Object[] { authParam.getUsername() },
                        LocaleContextHolder.getLocale()), null);
        } catch (IncorrectCredentialsException e) {
            return RestfulJsonModelAndView.buildError(Result.ERR_AUTH_USERNAME_PASSWORD, messageSource
                    .getMessage("Result.err.auth.password.incorrect", new Object[] {}, LocaleContextHolder.getLocale()),
                null);
        } catch (LockedAccountException e) {
            return RestfulJsonModelAndView.buildError(Result.ERR_AUTH_USER_IS_LOCK, messageSource
                    .getMessage("Result.err.auth.account.disabled", new Object[] {}, LocaleContextHolder.getLocale()),
                null);
        } catch (DisabledAccountException e) {
            return RestfulJsonModelAndView.buildError(Result.ERR_AUTH_USER_NOT_ACTIVED, messageSource
                    .getMessage("Result.err.auth.account.disabled", new Object[] {}, LocaleContextHolder.getLocale()),
                null);
        } catch (Exception e) {
            return RestfulJsonModelAndView
                .buildError(Result.ERR_INNER_SERVER, Result.MESSAGE_INNER_SERVER, e.getMessage());
        }
    }
}
